//
//  CallDirectoryHandler.m
//  CallKit
//
//  Created by 李园园 on 2017/4/17.
//  Copyright © 2017年 Goldencis. All rights reserved.
//

#import "CallDirectoryHandler.h"
@interface CallDirectoryHandler () <CXCallDirectoryExtensionContextDelegate>
@end

@implementation CallDirectoryHandler

//开始请求的方法，在打开设置-电话-来电阻止与身份识别开关时，系统自动调用
- (void)beginRequestWithExtensionContext:(CXCallDirectoryExtensionContext *)context {
    context.delegate = self;
    if (![self addBlockingPhoneNumbersToContext:context]) {
        NSError *error = [NSError errorWithDomain:@"CallDirectoryHandler" code:1 userInfo:nil];
        [context cancelRequestWithError:error];
        return;
    }
    
    if (![self addIdentificationPhoneNumbersToContext:context]) {
        NSError *error = [NSError errorWithDomain:@"CallDirectoryHandler" code:2 userInfo:nil];
        [context cancelRequestWithError:error];
        return;
    }
    
    [context completeRequestWithCompletionHandler:nil];
}

- (BOOL)addBlockingPhoneNumbersToContext:(CXCallDirectoryExtensionContext *)context {
    NSUserDefaults * userDefaults = [[NSUserDefaults alloc]initWithSuiteName:@"group.cn.neiwang.gview"];
    NSArray * array =  [userDefaults objectForKey:@"blackPhoneNum"];
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString * phoneStr  = obj;
        int64_t phoneInt = [phoneStr integerValue];
        CXCallDirectoryPhoneNumber  number = phoneInt ;
        [context addBlockingEntryWithNextSequentialPhoneNumber:number];
    }];
    return YES;
}

- (BOOL)addIdentificationPhoneNumbersToContext:(CXCallDirectoryExtensionContext *)context {
    NSUserDefaults * userDefaults = [[NSUserDefaults alloc]initWithSuiteName:@"group.cn.neiwang.gview"];
    NSArray * array =  [userDefaults objectForKey:@"blackPhoneNum"];
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString * phoneStr  = obj;
        int64_t phoneInt = [phoneStr integerValue];
        CXCallDirectoryPhoneNumber  number = phoneInt ;
        NSString *label = @"黑名单";
        [context addIdentificationEntryWithNextSequentialPhoneNumber:number label:label];
    }];
    return YES;
}

#pragma mark - CXCallDirectoryExtensionContextDelegate

- (void)requestFailedForExtensionContext:(CXCallDirectoryExtensionContext *)extensionContext withError:(NSError *)error {
}


@end
